//
//  CellContainTableView.m
//  mosad_hw_fin
//
//  Created by wyw on 2021/1/6.
//  Copyright © 2021 student9. All rights reserved.
//

#import <Foundation/Foundation.h>
#import "CellContainTableView.h"

@interface CellContainTableView() <UITableViewDelegate, UITableViewDataSource>

@end

@implementation CellContainTableView

- (void) GetDaily:(NSMutableArray *)array{
    for (int i = 0; i < array.count; ++i){
        NSLog(@"daily");
        Info * mydata = [[Info alloc] init];
        NSLog(@"%@",[array[i] valueForKey:@"Content"]);
        NSLog(@"%@",[NSString stringWithFormat:@"%@:%@", [array[i] valueForKey:@"Hour"],[array[i] valueForKey:@"Min"]]);
        mydata.descript = [NSString stringWithFormat:@"%@", [array[i] valueForKey:@"Content"]];
        mydata.indexID = [NSString stringWithFormat:@"%@", [array[i] valueForKey:@"Index"]];
        mydata.time = [NSString stringWithFormat:@"%@:%@", [array[i] valueForKey:@"Hour"],[array[i] valueForKey:@"Min"]];
        NSInteger Hour =[[NSString stringWithFormat:@"%@",[array[i] valueForKey:@"Hour"]] intValue];
        NSInteger Min =[[NSString stringWithFormat:@"%@",[array[i] valueForKey:@"Min"]] intValue];
        mydata.value = Hour*60+Min;
        mydata.week = 1;
        if (Min == 0){
            mydata.time = [NSString stringWithFormat:@"%@0",mydata.time];
        }
        NSLog(@"Hour %ld Min %ld value %ld", (long)Hour, (long)Min,(long)mydata.value);
        [self.datalist addObject:mydata];
    }
    [self.datalist sortUsingComparator:^NSComparisonResult(Info*  _Nonnull obj1, Info*  _Nonnull obj2) {
        if (obj1.value > obj2.value){
            return (NSComparisonResult)NSOrderedDescending;
        }else{
            return (NSComparisonResult)NSOrderedAscending;
        }
    }];
    self.count = 1;
}
- (void) GetWeekly:(NSMutableArray *)array{
    for (int i = 0; i < array.count; ++i){
        Info * mydata = [[Info alloc] init];
        mydata.descript = [NSString stringWithFormat:@"%@", [array[i] valueForKey:@"Content"]];
        mydata.time = [NSString stringWithFormat:@"%@:%@",[array[i] valueForKey:@"Hour"],[array[i] valueForKey:@"Min"]];
        NSInteger week =[[NSString stringWithFormat:@"%@",[array[i] valueForKey:@"Week"]] intValue];
        mydata.indexID = [NSString stringWithFormat:@"%@", [array[i] valueForKey:@"Index"]];
        mydata.week = week;
        NSInteger Hour =[[NSString stringWithFormat:@"%@",[array[i] valueForKey:@"Hour"]] intValue];
        NSInteger Min =[[NSString stringWithFormat:@"%@",[array[i] valueForKey:@"Min"]] intValue];
        mydata.value = week*24*60+Hour*60+Min;
        if (Min == 0){
            mydata.time = [NSString stringWithFormat:@"%@0",mydata.time];
        }
        NSLog(@"value %ld", (long)mydata.value);
        [self.datalist addObject:mydata];
    }
    [self.datalist sortUsingComparator:^NSComparisonResult(Info*  _Nonnull obj1, Info*  _Nonnull obj2) {
        if (obj1.value > obj2.value){
            return (NSComparisonResult)NSOrderedDescending;
        }else{
            return (NSComparisonResult)NSOrderedAscending;
        }
    }];
    self.count = 0;
    if (self.datalist.count > 0){
        NSInteger add = [self.datalist[0] week];
        NSInteger offset = 0;
        self.count = 1;
        for (int i = 0; i < self.datalist.count; ++i){
            if ([self.datalist[i] week] > add){
                add = [self.datalist[i] week];
                [self.weekcount addObject:[NSNumber numberWithInteger:offset]];
                self.count++;
            }
            offset++;
        }
        [self.weekcount addObject:[NSNumber numberWithInteger:offset]];
    }
}
- (void) GetOnetime:(NSMutableArray *)array{
    for (int i = 0; i < array.count; ++i){
        Info * mydata = [[Info alloc] init];
        mydata.descript = [NSString stringWithFormat:@"%@", [array[i] valueForKey:@"Content"]];
        mydata.time = [NSString stringWithFormat:@"%@.%@",[array[i] valueForKey:@"Month"],[array[i] valueForKey:@"Day"]];
        NSInteger Month =[[NSString stringWithFormat:@"%@",[array[i] valueForKey:@"Month"]] intValue];
        mydata.indexID = [NSString stringWithFormat:@"%@", [array[i] valueForKey:@"Index"]];
        NSInteger Day =[[NSString stringWithFormat:@"%@",[array[i] valueForKey:@"Day"]] intValue];
        mydata.value = Month*30+Day;
        mydata.week = 1;
        NSLog(@"value %ld", (long)mydata.value);
        [self.datalist addObject:mydata];
    }
    [self.datalist sortUsingComparator:^NSComparisonResult(Info*  _Nonnull obj1, Info*  _Nonnull obj2) {
        if (obj1.value >= obj2.value){
            return (NSComparisonResult)NSOrderedDescending;
        }else{
            return (NSComparisonResult)NSOrderedAscending;
        }
    }];
    self.count = 1;
}

- (void) initTable{
    self.datalist = [[NSMutableArray alloc] init];
    self.weekcount = [[NSMutableArray alloc] init];
    if (self.UserID == NULL){
        self.UserID = @"1220298052";
    }
    [self GetData];
    NSLog(@"time %lu", (unsigned long)self.datalist.count);
    UITableView * Mytable = [[UITableView alloc] init];
    Mytable.delegate = self;
    Mytable.dataSource = self;
    [self.contentView addSubview:Mytable];
    UIEdgeInsets edge = UIEdgeInsetsMake(10, 0, 0, 0);
    [Mytable mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.contentView).with.insets(edge);
    }];
    self.table = Mytable;
}

- (void)GetData{
    dispatch_semaphore_t semaphore= dispatch_semaphore_create(0);
    headimageModel *current_head_image = [headimageModel shareInstance];
    NSString *url = [NSString stringWithFormat:@"%@/%@/%@",current_head_image.host_str  ,self.Name, self.UserID];
    AFHTTPSessionManager *manage = [AFHTTPSessionManager manager];
    manage.completionQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    // 设置请求体为JSON
    manage.requestSerializer = [AFJSONRequestSerializer serializer];
    // 设置响应体为JSON
    manage.responseSerializer = [AFJSONResponseSerializer serializer];
    [manage GET:url parameters:nil headers:nil progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        //        NSLog(@"%@",responseObject);
        NSDictionary *dict = (NSDictionary *)responseObject;
        self.dict = dict;
        NSLog(@"signal");
        dispatch_semaphore_signal(semaphore);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"load data fail");
        dispatch_semaphore_signal(semaphore);
    }];
    dispatch_semaphore_wait(semaphore,DISPATCH_TIME_FOREVER);
    NSMutableArray * array;
    if ([[self.dict valueForKey:@"response"] isEqual:[NSNull null]]){
        array = [NSMutableArray new];
    }else{
        array = [self.dict valueForKey:@"response"];
    }
    if ([self.Name isEqualToString:@"Weekly"]){
        [self GetWeekly:array];
    }else if ([self.Name isEqualToString:@"Daily"]){
        [self GetDaily:array];
    }else if ([self.Name isEqualToString:@"Onetime"]){
        [self GetOnetime:array];
    }
}

#pragma TableviewDelegate TableviewDatasource;


// 删除
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (self.isshowingsection){
        return UITableViewCellEditingStyleDelete;
    }
    return  UITableViewCellEditingStyleNone;
}

- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath{
    return  @"删除";
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{
    if (editingStyle == UITableViewCellEditingStyleDelete){
        NSInteger indexId;
        if (self.weekcount.count == 0){
            indexId = indexPath.row;
        }else{
            if (indexPath.section == 0){
                indexId = indexPath.row;
            }else{
                indexId = [self.weekcount[indexPath.section-1] intValue] + indexPath.row;
            }
            for(int i = indexPath.section; i < self.weekcount.count; ++i){
                self.weekcount[i] = [NSNumber numberWithInt:[self.weekcount[i] intValue] - 1];
            }
        }
        headimageModel *current_head_image = [headimageModel shareInstance];
        NSString *url = [NSString stringWithFormat:@"%@/%@/%@",current_head_image.host_str  ,self.Name, [self.datalist[indexId] indexID]];
        NSLog(@"%@",url);
        AFHTTPSessionManager *manage = [AFHTTPSessionManager manager];
        // 设置请求体为JSON
        manage.requestSerializer = [AFJSONRequestSerializer serializer];
        // 设置响应体为JSON
        manage.responseSerializer = [AFJSONResponseSerializer serializer];
        
        [manage DELETE:url parameters:nil headers:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            NSLog(@"Delete success");
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            NSLog(@"Delete fail");
        }];
        [self.datalist removeObjectAtIndex:indexId];
        [self.table deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationRight];
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    NSLog(@"section all %ld",(long)section);
    if (self.weekcount.count == 0){
        if (self.isshowingsection || self.datalist.count == 0){
            return self.datalist.count;
        }else{
            return 1;
        }
    }else{
        if (self.isshowingsection){
            if (section == 0){
                return [self.weekcount[section] intValue];
            }else{
                return [self.weekcount[section] intValue] - [self.weekcount[section-1] intValue];
            }
        }else{
            return 1;
        }
    }
    //    return self.datalist.count;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
    if ([self.Name isEqualToString:@"Weekly"]){
        NSInteger ID = [self.weekcount[section] intValue] - 1;
        if (ID < 0){
            return nil;
        }
        Info * mydata = self.datalist[ID];
        NSString * res;
        switch (mydata.week) {
            case 1:
                res = @"周一";
                break;
            case 2:
                res = @"周二";
                break;
            case 3:
                res = @"周三";
                break;
            case 4:
                res = @"周四";
                break;
            case 5:
                res = @"周五";
                break;
            case 6:
                res = @"周六";
                break;
            case 7:
                res = @"周日";
                break;
            default:
                break;
        }
        return res;
    }
    return nil;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if ([self.Name isEqualToString:@"Weekly"]){
        return 20;
    }
    return 0;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (self.isshowingsection){
        return 40;
    }
    return 80;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSString *cellID = @"tcellID";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:cellID];
    }
    if (self.datalist.count != 0){
        NSLog(@"still working at cell create");
        Info * mydata;
        NSInteger realrow = indexPath.row;
        if (indexPath.section > 0){
            realrow = realrow + [self.weekcount[indexPath.section-1] intValue];
            NSLog(@"section %ld row %ld realrow %ld", (long)indexPath.section, (long)indexPath.row, (long)realrow);
        }
        mydata = self.datalist[realrow];
        NSLog(@"detail %@, time %@", mydata.descript,mydata.time);
        [cell.textLabel setText:mydata.descript];
        [cell.detailTextLabel setText:mydata.time];
    }
    else{
        [cell.textLabel setText:@"hello,world"];
        [cell.detailTextLabel setText:@"My friend"];
    }
    return cell;
}
@end
